// pages/coupon/detail.js
import api from '../../../api/index'
import { userInfoStore } from '../../../store/userInfo'
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userLevel: 0,
    coupon:null,
    imagePath: '',
    maskHidden: false,
    useCode: ''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({ 
      userLevel: userInfoStore.userInfo.level,
      coupon: { id: options.id}
    })
    
  },

  onShow: function () {
    api.getusercoupondetail({ userCouponId: this.data.coupon.id }).then(res => {
      this.setData({
        coupon: res.result
      });
    })
  },

  closeMask: function () {
    this.setData({
      maskHidden: !this.data.maskHidden
    });
  },

  topay:function(e){
    let coupon = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: '../../coupon/buy?couponId=' + coupon.couponId + '&userCouponId=' + coupon.id,
    })
  },

  /**确认使用 */
  submit: function (e) {
    let coupon = e.currentTarget.dataset.item;
    let param = {
      openId: userInfoStore.userInfo.openId,
      userCouponId: coupon.id
    }
    let self = this;
    api.userConfirmCoupon(param).then(res => {
      coupon.status=3;
      self.setData({ coupon: coupon});
      wx.showModal({
        title: '提示',
        content: '成功',
        showCancel: false
      })
    }, err => {
      wx.showToast({
        icon: "none",
        title: err
      })
    });
  },

  /**申请使用 */
  use: function (e) {
    let coupon = e.currentTarget.dataset.item;
    console.log(coupon);
    let p = userInfoStore.userInfo.phone;
    let code = coupon.id + '' + p.substr(p.length - 4);
    let self = this;
    let param = {
      openId: userInfoStore.userInfo.openId,
      userCouponId: coupon.id
    }
    api.applyCouponUse(param).then(res => {

      self.data.coupon.status = 6;
      self.setData({
        useCode: code,
        maskHidden: true,
        coupon: self.data.coupon
      });
      wx.showToast({
        icon: "none",
        title: "已成功发送"
      })
      
    }, err => {
      wx.showToast({
        icon: "none",
        title: err
      })
    });


  },

  /**申请退款 */
  applyRefund: function (e) {
    let self = this;
    let id = e.currentTarget.dataset.id;
    let param = {
      openId: userInfoStore.userInfo.openId,
      userCouponId: id
    }
    api.applyCouponRefund(param).then(res => {
      
      self.data.coupon.status = 4;
      self.setData({ coupon: self.data.coupon });
    }, err => {
      wx.showToast({
        icon: "none",
        title: err
      })
    });
  }
  
})